package databaseVersionControl.domain.db;

import databaseVersionControl.domain.dialect.Dialect;

public class Column implements DBComponent {
	
	private String name;
	private DataType type;
	private Integer size;
	private boolean notNull;
	private boolean isPrimaryKey;
	private ForeignKey foreignKey;

	public Column(String columnName) {
		this.name = columnName.toUpperCase();
	}
	
	public Column type(DataType type) {
		this.type = type;
		return this;
	}
	
	public Column size(Integer size) {
		this.size = size;
		return this;
	}
	
	public Column notNull() {
		notNull = true;
		return this;
	}
	
	public Column primaryKey() {
		isPrimaryKey = true;
		return this;
	}
	
	public Integer getSize() {
		return size;
	}
	
	public String getName() {
		return name;
	}

	public DataType getType() {
		return type;
	}
	
	public ForeignKey foreignKey() {
		this.foreignKey = new ForeignKey(this);
		return foreignKey;
	}

	@Override
	public String sqlInDialect(Dialect dialect) {
		String print = (size == null) ? name + " " + dialect.getType(type)
		: String.format("%s %s(%d)", getName(), dialect.getType(getType()), getSize());
		
		StringBuilder sb = new StringBuilder(print);
		if (notNull) sb.append(" NOT NULL");
		if (isPrimaryKey) sb.append(" PRIMARY KEY");
		if (foreignKey != null) sb.append(foreignKey.toString());
		
		return sb.toString();
	}

	@Override
	public String sqlIdentifier() {
		return "COLUMN " + getName();
	}

}